package com.lottery.im.module.chat.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.OnClick;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.fondesa.recyclerviewdivider.RecyclerViewDivider;
import com.lottery.im.MyApplication;
import com.lottery.im.R;
import com.lottery.im.base.BaseSwipeFragment;
import com.lottery.im.module.chat.adapter.DelGroupMemberAdapter;
import com.lottery.im.module.chat.presenter.DeleteGroupMemberPresenter;
import com.lottery.im.module.chat.view.DeleteGroupMemberView;
import com.lottery.im.module.tim.model.GroupMemberProfile;
import com.tencent.imsdk.TIMGroupMemberInfo;
import com.tencent.imsdk.TIMUserProfile;
import com.tencent.imsdk.TIMValueCallBack;
import com.tencent.imsdk.ext.group.TIMGroupManagerExt;
import com.tencent.imsdk.ext.group.TIMGroupMemberResult;
import java.util.ArrayList;
import java.util.List;

/**
 * 删除群成员（踢人）
 */
public class DeleteGroupMemberFragment extends BaseSwipeFragment<DeleteGroupMemberPresenter>
    implements DeleteGroupMemberView {

  private final static String ID_KEY = "ID_KEY";

  public static DeleteGroupMemberFragment create(String id) {
    DeleteGroupMemberFragment fragment = new DeleteGroupMemberFragment();
    Bundle b = new Bundle();
    b.putString(ID_KEY, id);
    fragment.setArguments(b);
    return fragment;
  }

  @BindView(R.id.tv_title) TextView mTvTitle;
  @BindView(R.id.list) RecyclerView mList;
  @BindView(R.id.btn_confirm) Button mBtnConfirm;

  private String mGroupId;

  private List<GroupMemberProfile> mGroupMemberInfos;
  private DelGroupMemberAdapter mAdapter;
  private ArrayList<String> mSelectIds = new ArrayList<>();

  @Override protected int getLayoutResId() {
    return R.layout.fragment_delete_group_member;
  }

  @Override protected void initPresenter() {
    presenter = new DeleteGroupMemberPresenter(getActivity(), this, this);
    presenter.init();
  }

  @Override public void initView() {

    mGroupId = getArguments().getString(ID_KEY);

    mTvTitle.setText("踢出群聊");
    mGroupMemberInfos = new ArrayList<>();
    mList.setLayoutManager(new LinearLayoutManager(mActivity));
    RecyclerViewDivider.with(mActivity)
        .color(ContextCompat.getColor(mActivity, R.color.windowBackground))
        .size((int) mActivity.getResources().getDimension(R.dimen.line_size))
        .hideLastDivider()
        .build()
        .addTo(mList);
    mAdapter = new DelGroupMemberAdapter(mGroupMemberInfos, mSelectIds);
    mAdapter.setOnItemClickListener((adapter, view, position) -> setCheck(position));
    mList.setAdapter(mAdapter);
    presenter.getGroupMembers(mGroupId);
  }

  @OnClick({ R.id.iv_back, R.id.btn_confirm }) public void onViewClicked(View view) {
    switch (view.getId()) {
      case R.id.iv_back:
        popBackStack();
        break;
      case R.id.btn_confirm:
        confirm();
        break;
    }
  }

  /**
   * 拉取那些非好友的成员资料
   * 由于tim返回群成员的信息是没有头像跟昵称的
   */
  private void getUsersProfile() {
    List<String> ids = new ArrayList<>();
    for (GroupMemberProfile memberInfo : mGroupMemberInfos) {
      if (TextUtils.isEmpty(memberInfo.getAvatarUrl())) {
        ids.add(memberInfo.getIdentify());
      }
    }
    if (ids.size() > 0) presenter.getUsersProfile(ids);
  }

  /**
   * @param position 点击的position
   * 修改选择状态
   */
  private void setCheck(int position) {

    if (mGroupMemberInfos.get(position)
        .getIdentify()
        .equals(MyApplication.getInstance().getThirdAccId())
        || mGroupMemberInfos.get(position).getIdentify().equals(MyApplication.getInstance().getUserInfo().getQqServiceName())
        || mGroupMemberInfos.get(position).getIdentify().equals(MyApplication.getInstance().getUserInfo().getQqFeedBackName())
        ) {
      return;
    }

    if (mSelectIds.contains(mGroupMemberInfos.get(position).getIdentify())) {
      mSelectIds.remove(mGroupMemberInfos.get(position).getIdentify());
    } else {
      mSelectIds.add(mGroupMemberInfos.get(position).getIdentify());
    }
    mAdapter.setSelectIds(mSelectIds, position);
    if (mSelectIds.size() > 0) {
      mBtnConfirm.setEnabled(true);
    } else {
      mBtnConfirm.setEnabled(false);
    }
  }

  /**
   * 选择完成，确定踢人
   */
  private void confirm(){
    showLoadingDialog();
    TIMGroupManagerExt.DeleteMemberParam param = new TIMGroupManagerExt.DeleteMemberParam(mGroupId, mSelectIds);
    TIMGroupManagerExt.getInstance().deleteGroupMember(param,
        new TIMValueCallBack<List<TIMGroupMemberResult>>() {
          @Override public void onError(int i, String s) {
            showToast("踢出失败，请稍后再试～");
            cancelLoadingDialog();
          }

          @Override public void onSuccess(List<TIMGroupMemberResult> timGroupMemberResults) {
            cancelLoadingDialog();
            setFragmentResult(RESULT_OK,new Intent());
            popBackStack();
          }
        });



  }

  @Override public void showMemberInfo(List<TIMGroupMemberInfo> timGroupMemberInfos) {
    mGroupMemberInfos.clear();
    for (TIMGroupMemberInfo info : timGroupMemberInfos) {
      mGroupMemberInfos.add(new GroupMemberProfile(info));
    }
    mAdapter.notifyDataSetChanged();
    getUsersProfile();
  }

  @Override public void refreshUsersProfile(List<TIMUserProfile> timUserProfiles) {
    for (int i = 0; i < mGroupMemberInfos.size(); i++) {
      for (TIMUserProfile userProfile : timUserProfiles) {
        if (mGroupMemberInfos.get(i).getIdentify().equals(userProfile.getIdentifier())) {
          mGroupMemberInfos.get(i).setAvatarUrl(userProfile.getFaceUrl());
          mGroupMemberInfos.get(i).setName(userProfile.getNickName());
          mGroupMemberInfos.get(i).setNickName(userProfile.getNickName());
          break;
        }
      }
    }
    mAdapter.notifyDataSetChanged();
  }
}
